from flask import *
from redissession import RedisSessionInterface
from controllers.signupController import *
from controllers.signinController import *
from models import *
from databaseHandler import db
import os

app=Flask(__name__)

app.session_interface = RedisSessionInterface()

app.secret_key = 'dwqiuajefhbnw8qyegf2378r6tfg3q4f78g!@#$&)(U*BVGFYRT^$%E&%^&(Y@(&G!)))'

db.generate_mapping(create_tables=True)

def userAuthorized(func):
    def wrapper(*args,**kargs):
        if session.get('signin')==True:
            return func(**kargs)
        else:
            return redirect(url_for('doSignin'))
    return wrapper


@app.route('/favicon.ico')
def favicon():
    return send_from_directory(os.path.join(app.root_path, 'static'),
                               'favicon.ico', mimetype='image/vnd.microsoft.icon')

@app.route('/')
@app.route('/index')
def doIndex():
    return render_template('Index.html')


@app.route('/signup',methods=['POST','GET'])
def doSignup():
    if request.method == 'GET':
        return render_template('Signup.html')
    elif request.method == 'POST':
        Email = request.form['email']
        nickName = request.form['nickname']
        passWord = request.form['password']
        tel = request.form['tel']
        if newUserWithoutInviteCode(Email,nickName,tel,passWord)==1:
            return redirect(url_for('doIndex'))
        else:
            return render_template('Signup.html')

    
@app.route('/signin',methods=['GET','POST'])
def doSignin():
    if request.method == 'GET':
        return render_template('Signin.html')
    elif request.method == 'POST':
        Email = request.form['email']
        passWord = request.form['password']
        user=checkPassword(Email,passWord)
        if user!=0:
            session['Email']=Email
            session['signin']=True
            session['nickName']=user.nickName
            return redirect(url_for('doIndex'))
        else:
            return render_template('Signin.html',error=1)


@app.route('/signout')
def doSignout():
    session.clear()
    return redirect(url_for('doIndex'))


@app.route('/newarticle',methods=['GET','POST'])
@userAuthorized
def doNewArticle():
    if request.method == 'GET':
        return render_template('NewArticle.html')
    elif request.method == 'POST':
        articleTitle = request.form['articletitle']
        articleContents = request.form['articlecontents']
        articleTag = request.form['articletag']


app.debug=True
